package com.lapuda.singleton;

/**
 * @author shundong.li
 * @date 2022/1/21
 */
public class DoubleCheckedLock {
    //volatile关键字修饰该对象，禁止指令重排
    private volatile static DoubleCheckedLock singleton;
    //私有化构造方法 只能通过静态方法getSingleton获得对象
    private DoubleCheckedLock (){}
    public static DoubleCheckedLock getSingleton() {
        //先判断对象是否已经实例过，没有实例化过才进入加锁代码，
        //加锁会增加开销，第一次简单的判断（不加锁）能提高执行效率
        if (singleton == null) {
            synchronized (DoubleCheckedLock.class) {
                if (singleton == null) {
                    singleton = new DoubleCheckedLock();
                }
            }
        }
        return singleton;
    }
}
class test{
    public static void main(String[] args) {
        DoubleCheckedLock singleton1 = DoubleCheckedLock.getSingleton();
        DoubleCheckedLock singleton2 = DoubleCheckedLock.getSingleton();
        System.out.println(singleton1.hashCode()==singleton2.hashCode());
        System.out.println(singleton1==singleton2);
        System.out.println(singleton1.equals(singleton2));

    }
}